package com.block.sms.service.send;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.block.common.constant.AppRspCodeConstant;
import com.block.db.entity.SmsConfigInfo;
import com.block.db.entity.SmsTemplate;
import com.block.sms.dto.SmsBalanceDTO;
import com.block.sms.dto.SmsResultDTO;
import com.block.sms.service.ISmsSendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class BeiYuSmsSendServiceImpl implements ISmsSendService {

    @Override
    public SmsResultDTO sendSms(String mobile, String outId, SmsTemplate smsTemplate, SmsConfigInfo smsConfigInfo, JSONObject paramObject) {

        SmsResultDTO  resultDTO = new SmsResultDTO();
        try {
            JSONArray paramArr = paramObject.getJSONArray("paramArr");
            paramArr.stream().toArray();

            HttpRequest httpRequest = HttpUtil.createPost(smsConfigInfo.getUrl());
            httpRequest.header("Accept", "application/json");
            httpRequest.header("Content-Type", "application/json;charset=utf-8");

            String username = smsConfigInfo.getAccount();
            String timestamp = String.valueOf(System.currentTimeMillis());
            String sign = SecureUtil.md5(username+timestamp+SecureUtil.md5(smsConfigInfo.getSecret()));

            String content = StrUtil.format(smsTemplate.getTemplateContext(), paramArr.stream().toArray());

            JSONObject dataJson = new JSONObject();
            dataJson.put("phone", mobile);
            dataJson.put("content", content);
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(dataJson);

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("userName", username);
            paramMap.put("timestamp", timestamp);
            paramMap.put("messageList", jsonArray);
            paramMap.put("sign", sign);

            httpRequest.body(JSON.toJSONString(paramMap));

            String bodyResult = httpRequest.execute().body();
            log.info("【北屿短信服务】发送结束【requesturl】{}【paramMap】{}【bodyResult】{}",
                    smsConfigInfo.getUrl(), JSON.toJSONString(paramMap), bodyResult);

            JSONObject resultJson = JSON.parseObject(bodyResult);
            Integer code = resultJson.getInteger("code");
            String message = resultJson.getString("message");
            JSONArray dataArray = resultJson.getJSONArray("data");

            if (ObjectUtil.equals(Integer.valueOf("0"), code)){
                JSONObject jsonObject = dataArray.getJSONObject(0);
                Integer itemCode = jsonObject.getInteger("code");
                String phone = jsonObject.getString("phone");
                String itemMessage = jsonObject.getString("message");
                Long msgId = jsonObject.getLong("msgId");
                if (ObjectUtil.equals(Integer.valueOf("0"), itemCode) && StrUtil.equals(mobile, phone)){
                    resultDTO.setCode(AppRspCodeConstant.SUCCESS);
                    resultDTO.setHttpStatus(String.valueOf(itemCode));
                    resultDTO.setRequestId(outId);
                    resultDTO.setMessage(JSON.toJSONString(jsonObject));
                    return resultDTO;
                }
            }
            resultDTO.setMessage(bodyResult);
        } catch (Exception exception) {
            log.error(String.format("【北屿短信服务】发送发生异常【mobile】%s【code】%s", mobile, paramObject.toJSONString()), exception);
        }
        resultDTO.setCode(AppRspCodeConstant.OPERATION_FAILURE);
        return resultDTO;
    }

    @Override
    public SmsBalanceDTO queryBalanceInfo(SmsConfigInfo smsConfigInfo) {
        return null;
    }

}
